<template>
    <div>
        <div style="display: flex;">
            <el-input v-model="roomId" placeholder="Please input" />
            <el-button type="primary" @click="requestState">call</el-button>
        </div>
        <div id="videos"></div>
    </div>
</template>

<script setup lang="ts">
import io from 'socket.io-client'
import {userStore} from '../../../../store/index'
import { ref } from 'vue';
import {ElMessage} from 'element-plus'
// import { tr } from 'element-plus/es/locale/index.mjs';
const store = userStore()


// data
let roomId = ref('123')
// 帮助服务器找到ip和通信设备
var iceServers = {
    iceServers: [
        { urls: 'stun:stun.services.mozilla.com' },
        { urls: 'stun:stun.schlund.de' },
        { urls: 'stun:stun1.l.google.com:19302' }
    ]
}
let pc = new RTCPeerConnection(iceServers)
const configure = {video:true,audio:true}
let stream:any;
// listenEvent hostname
const socket = io(`http://${location.hostname}:9003`,{
    query: {
        userId : store.userInfo.phone
    }
})
socket.on('connection',(data)=>{
    console.log(data);
})
socket.on('joined',joinedFunction)
socket.on('offer',offerFunction)
socket.on('answer',answerFunction)
socket.on('candidate',candidateFunction)
pc.onicecandidate = onicecandidateFunction
pc.ontrack = ontrackFunction

//  methods
// 加入房间，获取本端的媒体流发送给对端
async function requestState(){
    if(!roomId.value){
        ElMessage.error('会议号不能为空')
        return
    }
    // 加入房间
    socket.emit('join',{
        roomId:roomId.value,
        userId: store.userInfo.phone
    })
    stream = await navigator.mediaDevices.getUserMedia(configure)
    stream.getTracks().forEach((track:any)=>{
        pc.addTrack(track,stream)
    })
    const video = document.createElement('video')
    const videos = document.getElementById('videos')
    video.srcObject = stream
    video.height = 100
    video.width = 100
    video.autoplay = true
    video.loop = true
    videos?.appendChild(video)
    const offer = await pc.createOffer()
    await pc.setLocalDescription(offer)
    socket.emit('offer',{
        roomId:roomId.value,
        userId: store.userInfo.phone,
        offer
    })
}
// 监听加入房间信息
function joinedFunction(data:any){
    console.log("joinedFunction",data.message);
}
// 监听对端的answer信息
async function answerFunction(data:any){
    await pc.setRemoteDescription(data.answer)
}
// 监听对端的offer信息
async function offerFunction(data:any){
    await pc.setRemoteDescription(data.offer)
    let str = await navigator.mediaDevices.getDisplayMedia(configure)
    str.getTracks().forEach((track:any)=>{
        pc.addTrack(track,str)
    })
    const answer = await pc.createAnswer()
    await pc.setLocalDescription(answer)
    socket.emit('answer',{
        roomId:roomId.value,
        userId: store.userInfo.phone,
        answer
    })
}
// 监听对端的数据流
function ontrackFunction(event:any){
    console.log('ontrackFunction',event);
    const video = document.createElement('video')
    const videos = document.getElementById('videos')
    video.srcObject = event.streams[0]
    video.height = 100
    video.width = 100
    video.autoplay = true
    video.loop = true
    videos?.appendChild(video)
}
// 监听pc协商完成后，获取本段的公网信息发送给对端
function onicecandidateFunction(event:any){
    console.log('onicecandidateFunction',event);
    socket.emit('candidate',{
        roomId:roomId.value,
        userId: store.userInfo.phone,
        candidate:event.candidate
    })
}
// 接收和存储对端的candidate信息
function candidateFunction(data:any){
    console.log('onicecandidateFunction',event);
    const candidate = new RTCIceCandidate(data.candidate)
    pc.addIceCandidate(candidate)
}





</script>

<style scoped>

</style>